<template>
  <Wrapper v-if="isReging">
    <view class="inner-wrapper" style="padding-bottom: 100px">
      <view style="height:17px"></view>
      <view class="realname-block" style=" margin: 0 16px 17px 16px;">
        <view class="realname-block-input-wrapper column">
          <view class="zjzhangpain">上传身份证</view>
          <view class="realname-block-upload-wrapper">
            <view class="realname-block-upload" @click="upload('front')">
              <view class="realname-block-upload-image-box">
                <image
                  class="realname-block-upload-image"
                  :src="positiveSrc"
                  mode="aspectFit"
                />
                <image
                  class="realname-block-upload-icon"
                  :src="uploadIcon"
                  mode="aspectFit"
                />
              </view>
              <view class="realname-block-upload-tip">添加身份证正面</view>
            </view>
          </view>
        </view>
      </view>
      <!-- 身份认证 -->
      <view style="background:#fff;margin: 0 16px; border-radius: 8px;">
        <view style="padding: 16px;padding-bottom: 10px;">
          <view class="zjzhangpain">身份信息</view>
        </view>
        <view class="bgc-light" style="margin: 0 16px; margin-bottom: 16px; border-radius: 8px; display: flex; align-items: center; padding: 8px; justify-content: space-between">
          <view class="tc-theme">绑定微工卡方式，需先授权微信授权</view>
          <view v-if="showWXBtn">
            <button
              class="block-button-wx bgc-theme"
              open-type="getUserInfo"
              @getuserinfo="getUserInfo"
              v-if="!canIUseGetUserProfile"
            >
              <text>去授权</text>
            </button>
            <button
              class="block-button-wx bgc-theme"
              :disabled="disabled"
              @click="getUserProfile"
              v-if="canIUseGetUserProfile"
            >
              <text>去授权</text>
            </button>
          </view>
          <view v-else>
            <button
              class="block-button-wx bgc-theme"
              :disabled="disabled"
            >
              <text>已授权</text>
            </button>
          </view>
        </view>
        <XqFormBuild
          v-if="showForm"
          ref="form"
          :dynamic-data="{}"
          :form="form"
          :sortedKeys="sortedKeys"
          :formConfig="formConfig"
          :rules="rules"
          :selectMap="selectMap"
          :tempData="tempData"
          labelPosition="left"
          labelWidth="180"
          placeholderStyle="text-align: right"
          @update="onFormUpdate"
        >
          <view slot="zfbtip" style="display: flex; align-items: flex-start; padding: 8px 0">
            <u-icon name='info-circle-fill' :color="settings.theme" size="28" style="margin-top: 2px" />
            <view style="margin-left: 4px; color: rgba(154, 152, 152, 1); font-size: 12px">打开支付宝，点击右下角“我的”，点击支付宝头像，即可看到支付宝账号。</view>
          </view>
          <u-form-item
            label="微工卡"
            slot="wgk"
            :required="wgkRequired"
            labelWidth="120"
          >
            <view v-if="showWXBtn" style="display: flex; justify-content: flex-end; align-items: center">
              <view style="color: rgba(179, 179, 179, 1)">去绑定</view>
              <u-icon name="arrow-right" color="rgba(179, 179, 179, 1)" size="28" style="margin-left: 4px" />
            </view>
            <view v-else style="display: flex; justify-content: flex-end; align-items: center">
              <view v-if="showXGKBindBtn" class="tc-theme" @click="buildToken">去绑定</view>
              <view v-if="showXGKJumpBtn && wgkInfo" class="tc-theme" @click="JumpToWGK">已绑定</view>
              <u-icon name="arrow-right" color="rgba(179, 179, 179, 1)" size="28" style="margin-left: 4px" />
            </view>
          </u-form-item>
          <u-icon name="camera" size="32" slot="bankCard" @click="upload('bankCard')" />
        </XqFormBuild>
      </view>
    </view>
    <view class="block-buttonBox">
      <button class="block-button" @click="confirm" :disabled="conDisabled">
        确认
      </button>
    </view>
  </Wrapper>
  <view
    v-else
    style="width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; flex-direction: column"
  >
    <image :src="successIcon" mode="aspectFit" style="padding: 0; width: 40%" />
    <view>登记完成</view>
    <view style="margin-top: 12px">请点击左上角退出</view>
  </view>
</template>
<script>
import Wrapper from "@/components/Wrapper";
import XqFormBuild from "@/components/XqForm2/XqFormBuild/fxdj";
import { buildForm, handleTailValue } from "@/components/XqForm2/utils";
import { mapState } from 'vuex'
import {
  submitInfoReq,
  XGKCheckReq,
  getOpenidReq,
  buildAuthTokenReq
} from "./api";
import FormJson from "./formJson";
import {
  uploadGeneralImgIdCard,
  uploadGeneralBankCard
} from "@/services/common";

export default {
  name: "",
  components: {
    Wrapper,
    XqFormBuild
  },
  mixins: [],
  props: {},
  data() {
    // 从携带的参数中获取批次类型，如果是支付宝那么支付宝账号必填
    const stor = uni.getStorageSync("redirectUrl");
    console.log("发薪登记参数", stor);
    const fields = JSON.parse(JSON.stringify(FormJson.fields));
    if (stor && stor.includes('batchType":"1"')) {
      fields["zfbIdentity"]["decorator"]["rules"][0]["required"] = true;
    }
    if (stor && stor.includes('batchType":"3"')) {
      fields["bankCard"]["decorator"]["rules"][0]["required"] = true;
    }
    const wgkRequired = stor && stor.includes('batchType":"2"')

    const { form, formConfig, rules, selectMap } = buildForm(fields);

    return {
      isReging: true,
      successIcon: require("./images/wancheng.png"),
      positiveSrc: require("./images/shenfenzhengzheng.png"),
      uploadIcon: require("./images/camera.png"),
      sortedKeys: ["name", "idCard", "zfbIdentity"],
      FormJson,
      form,
      formConfig,
      rules,
      selectMap,
      tempData: {
        name: null,
        idCard: null,
        phone: null,
        zfbIdentity: null,
        unionId: null,
        openId: null,
        bankCard: null,
        openingBank: null
      },
      showForm: false,
      conDisabled: false,
      bankCardUrl: null,
      showWXBtn: true,
      showXGKBindBtn: false, // 显示微工卡绑定按钮
      showXGKJumpBtn: false, // 显示微工卡查看按钮
      jsCode: null,
      canIUseGetUserProfile: false,
      disabled: false,
      options: {}, // 携带进来的参数
      wxInfo: {}, // 微信授权
      wgkInfo: null, // 微工卡跳转信息
      formInfo: {}, // 表单缓存
      wgkRequired
    };
  },
  computed: {
    ...mapState(['settings'])
  },
  watch: {
    wxInfo(newVal) {
      console.log('wxInfo watch', newVal);
      if (newVal && newVal.openId) {
        this.showWXBtn = false;
        XGKCheckReq(newVal.openId, this.options.siteId)
          .then(res => {
            console.log('微工卡绑定查询', res);
            if (res) {
              this.wgkInfo = {
                appid: newVal.appId,
                mchid: res.mchid,
                sub_mchid: res.sub_mchid,
                openid: res.openid
              }
              uni.setStorageSync('wgkInfo', JSON.stringify(this.wgkInfo))

              if (res.authorize_state !== "AUTHORIZED") {
                this.showXGKBindBtn = true;
                this.showXGKJumpBtn = false;
              } else {
                this.showXGKJumpBtn = true;
                this.showXGKBindBtn = false;
              }
              this.showForm = false;
              this.$nextTick(() => {
                this.showForm = true;
              })
            } else {
              console.log("商户或租户错误，查询不到微工卡信息");
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    },
    showForm(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.init();
          }
        })
      }
    }
  },
  onLoad(options) {
    // 1. 保存携带的参数
    this.options = options;
    uni.setStorageSync('cacheInfo', JSON.stringify(options))

    // 2. 判断授权方法
    if (wx.getUserProfile) {
      this.canIUseGetUserProfile = true;
    }

    // 3. 提前获取 jsCode
    uni.login({
      provider: "weixin",
      success: loginRes => {
        this.jsCode = loginRes.code;
      }
    });
  },
  onShow() {
    console.log("发薪登记");

    // 1. 微工卡缓存信息
    const wgkInfoTemp = uni.getStorageSync('wgkInfo')
    console.log('wgkInfoTemp', wgkInfoTemp);
    if (wgkInfoTemp) {
      this.wgkInfo = JSON.parse(wgkInfoTemp);
    }

    // 2. 参数缓存信息
    let cacheInfoTemp = uni.getStorageSync('cacheInfo')
    console.log('cacheInfoTemp', cacheInfoTemp);
    if (cacheInfoTemp) {
      this.options = JSON.parse(cacheInfoTemp);
    }

    // 3. 微信授权的缓存信息
    let wxInfoTemp = uni.getStorageSync('wxInfo')
    console.log('wxInfoTemp', wxInfoTemp);
    if (wxInfoTemp) {
      this.wxInfo = JSON.parse(wxInfoTemp);
    }

    // 4. 表单缓存
    let formInfoTemp = uni.getStorageSync('formInfo')
    console.log('formInfoTemp', formInfoTemp);
    if (formInfoTemp) {
      this.formInfo = JSON.parse(formInfoTemp);
      this.tempData = {
        ...this.tempData,
        ...this.formInfo
      }
    }
  },
  created() {},
  mounted() {
    this.showForm = true;
  },
  destroyed() {
    uni.removeStorageSync('')
  },
  methods: {
    confirm() {
      this.$refs.form
        .getData()
        .then(res => {
          submitInfoReq({
            ...res,
            siteId: this.options.siteId,
            batchId:
              this.options.batchId && this.options.batchId !== "undefined"
                ? this.options.batchId
                : null,
            unionId: this.wxInfo.unionId,
            openId: this.wxInfo.openId,
            idCardUrl: this.positiveSrc,
            bankCardUrl: this.bankCardUrl,
            avatar: this.wxInfo.avatarUrl,
            nickName: this.wxInfo.nickName,
          })
            .then(() => {
              uni.showToast({
                title: "提交成功",
                duration: 2000
              });
              this.isReging = false;
            })
            .catch(err => {
              console.log("ERROR: ", err);
              uni.showToast({
                title: "提交失败",
                duration: 2000
              });
            });
        })
        .catch(err => {
          console.log("debug log --> ", err);
        });
    },
    onFormUpdate(tail, value) {
      handleTailValue(tail, value, this);
      this.getFormChange(tail, value);
    },
    getFormChange(tail, value) {
      if (tail === "form.idCard") {
        value = value ? value.toUpperCase() : null;
        this.$set(this.form, "idCard", value);
      }
      const tailArr = tail.split('.')
      this.tempData = {
        ...this.tempData,
        [tailArr[tailArr.length - 1]]: value
      };
    },
    upload(e) {
      uni.chooseImage({
        count: 1,
        success: imageRes => {
          const tempFilePaths = imageRes.tempFilePaths;
          this.conDisabled = true;
          uni.showLoading({
            title: "识别中...",
            mask: true
          });
          if (e === "bankCard") {
            uploadGeneralBankCard(tempFilePaths[0])
              .then(res => {
                uni.hideLoading();
                if (JSON.stringify(res) !== "{}" && res.bankCardNumber) {
                  this.bankCardUrl = res.url;
                  this.$set(this.form, "bankCard", res.bankCardNumber);
                  // this.$set(this.form, "openingBank", res.bankName);
                  this.tempData = {
                    ...this.tempData,
                    bankCard: res.bankCardNumber,
                    // openingBank: res.bankName
                  };
                }
                this.conDisabled = false;
              })
              .catch(err => {
                console.log(err);
                uni.hideLoading();
                uni.showToast({
                  title: err.message,
                  icon: "none",
                  duration: 1500
                });
                this.conDisabled = false;
              });
          } else {
            uploadGeneralImgIdCard(tempFilePaths[0], e)
              .then(res => {
                uni.hideLoading();
                if (JSON.stringify(res) !== "{}" && res.name) {
                  this.positiveSrc = res.url;
                  this.$set(this.form, "name", res.name);
                  this.$set(this.form, "idCard", res.idcard);
                  this.tempData = {
                    ...this.tempData,
                    name: res.name,
                    idCard: res.idcard
                  };
                }
                this.conDisabled = false;
              })
              .catch(err => {
                uni.hideLoading();
                uni.showToast({
                  title: err.message,
                  icon: "none",
                  duration: 1500
                });
                this.conDisabled = false;
              });
          }
        },
        fail: err => {
          uni.showToast({
            title: err.message,
            icon: "none",
            duration: 1500
          });
        }
      });
    },
    JumpToWGK() {
      uni.setStorageSync('wgkJump', '查看 start')
      uni.setStorageSync('formInfo', JSON.stringify(this.tempData))
      wx.navigateToMiniProgram({
        appId: "wxd24d9057cd83d47a",
        path: `/pages/card/card?appid=${this.wgkInfo.appid}&mchid=${this.wgkInfo.mchid}&sub_mchid=${this.wgkInfo.sub_mchid}&openid=${this.wgkInfo.openid}`,
        success: (aRes) => {
          console.log('微工卡查看跳转成功', aRes);
          uni.setStorageSync('wgkJump', '查看 success')
        },
        fail: (err) => {
          console.log('微工卡查看跳转失败', err);
          uni.setStorageSync('wgkJump', '查看 fail')
          uni.showToast({
            title: '绑定失败',
            duration: 2000
          });
        }
      })
    },
    buildToken() {
      if (!this.tempData.idCard || !this.tempData.name) {
        uni.showToast({
          title: '绑定前请先补全姓名身份证号',
          duration: 2000
        })
        return
      }
      buildAuthTokenReq(this.options.siteId, {
          openid: this.wxInfo.openId,
          user_name: this.tempData.name,
          id_card_number: this.tempData.idCard
        })
        .then(res => {
          console.log('微工卡绑定参数', res);
          uni.setStorageSync('wgkJump', '绑定 start')
          uni.setStorageSync('formInfo', JSON.stringify(this.tempData))
          uni.showModal({
            title: '跳转提示',
            content: '绑定动作需要跳转到微信官方的微工卡小程序中完成，职薪人无法获取您的任何账户信息，请放心！',
            showCancel: false,
            confirmText: '前去绑定',
            success: () => {
              wx.navigateToMiniProgram({
                appId: "wxd24d9057cd83d47a",
                path: `/pages/card/auth?appid=${res.appid}&mchid=${res.mchid}&sub_mchid=${res.sub_mchid}&openid=${res.openid}&token=${res.token}`,
                success: (aRes) => {
                  console.log('微工卡绑定跳转成功', aRes);
                  uni.setStorageSync('wgkJump', '绑定 success')
                },
                fail: (err) => {
                  console.log('微工卡绑定跳转失败', err);
                  uni.setStorageSync('wgkJump', '绑定 fail')
                  uni.showToast({
                    title: '绑定失败',
                    duration: 2000
                  });
                }
              })
            }
          })
        })
        .catch(err => {
          console.log(err);
        })
    },
    // 微信授权
    getUserProfile: function(e) {
      this.disabled = true;
      wx.getUserProfile({
        desc: "获取你的昵称、头像", // 不写不弹提示框
        success: res => {
          uni.showLoading({
            title: "信息验证中...",
            mask: true
          });
          this.disabled = false;
          this.getOpenId({
            iv: res.iv,
            encryptedData: res.encryptedData,
            jsCode: this.jsCode
          });
          uni.hideLoading();
        },
        fail: res => {
          this.disabled = false;
          // 拒绝授权
          wx.showToast({
            title: "微信授权失败",
            icon: "none"
          });
          return;
        }
      });
    },
    getUserInfo(res) {
      if (res.detail && res.detail["iv"] && res.detail["encryptedData"]) {
        this.getOpenId({
          iv: res.detail.iv,
          encryptedData: res.detail.encryptedData,
          jsCode: this.jsCode
        })
      } else {
        uni.showToast({
          title: "微信授权失败",
          icon: "none",
          duration: 2000
        });
      }
    },
    getOpenId(data) {
      getOpenidReq(data)
        .then(res => {
          this.wxInfo = res;
          uni.setStorageSync('wxInfo', JSON.stringify(res))
        })
        .catch(err => {
          console.log(err);
        });
    }
  }
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
::v-deep .form_warp {
  padding-bottom: 0;
}
::v-deep .u-form-item--left__content--required {
  left: -10px;
}
::v-deep .uni-input-input {
  text-align: right;
}
::v-deep .u-form-item__message {
  text-align: right;
}
.inner-wrapper {
  width: 100vw;
  min-height: 100vh;
  background: #f8f8f8;
  overflow-y: auto;
}
.realname-block {
  border-radius: 8px;
  margin-bottom: 20px;
  padding: 16px;
  background-color: #ffffff;
  .realname-block-input-wrapper {
    display: flex;
    flex-direction: row;
    padding: 0;
    justify-content: space-between;
    color: #ccc;
    &.border {
      border-bottom: 0.5px solid rgba(0, 0, 0, 0.1);
    }
    &.column {
      flex-direction: column;
      justify-content: flex-start;
    }
    .borderLast {
      border-bottom: 0px;
    }
    .realname-block-input-label {
      &:before {
        content: "*";
        color: #fa5051;
        margin-right: 5px;
      }
    }
    .realname-block-input {
      text-align: right;
    }
    .realname-block-upload-wrapper {
      width: 100%;
      margin-top: 10px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      .realname-block-upload-image-box {
        position: relative;
        .realname-block-upload-icon {
          position: absolute;
          width: 40px;
          height: 40px;
          top: 50%;
          left: 50%;
          margin-top: -32px;
          margin-left: -32px;
          padding: 12px;
          border-radius: 50%;
          background: rgba(0, 0, 0, 0.3);
        }
      }
      .realname-block-upload {
        width: 100%;
        box-sizing: border-box;
        border: 1px dashed #a9a7a6;
        border-radius: 5px;
        overflow: hidden;
        .realname-block-upload-image {
          width: 100%;
          height: 117px;
          // background-color: #f7f7f7;
          padding: 12px 16px 0px;
          box-sizing: border-box;
        }
        .realname-block-upload-tip {
          width: 100%;
          color: #354785;
          text-align: center;
          line-height: 20px;
          // height: 24px;
          font-size: 14px;
          padding-bottom: 4px;
        }
      }
    }
  }
}
.block-wrapper {
  padding-left: 15px;
  padding-right: 15px;
  padding-bottom: 15px;
  &.nph {
    padding-left: 0;
    padding-right: 0;
  }
  &.pt {
    padding-top: 15px;
  }
  .block-inner {
    background-color: #ffffff;
    border-radius: 8px;
    background-color: #ffffff;
    border-radius: 8px;
    padding: 16px;
    padding-top: 0;
    &.theme {
      background-color: #1890ff;
    }
    &.pt {
      padding-top: 15px;
    }
    &.input {
      padding-top: 13px;
      padding-bottom: 5px;
    }
    &.mt {
      margin-top: 15px;
    }
  }

  .block-tip {
    font-size: 12px;
    color: #999;
    line-height: 35px;
    padding: 0 10px;
    &.np {
      line-height: 1;
      padding: 0;
    }
  }
  .block-inner-content {
    margin-top: 15px;
    color: #999;
    font-size: 14px;
    line-height: 1.75;
  }
  .block-input-wrapper {
    display: flex;
    flex-direction: row;
    padding: 10px 0;
    justify-content: space-between;
    // color: #999;
    font-size: 14px;
    align-items: center;
    &.border {
      border-bottom: 0.5px solid rgba(0, 0, 0, 0.1);
    }
    &.column {
      flex-direction: column;
      justify-content: flex-start;
    }
    .borderLast {
      border-bottom: 0px;
    }
    .block-input-label {
      width: 80px;
      &.required {
        &:before {
          content: "*";
          color: #fa5051;
          margin-right: 5px;
        }
      }
    }
    .block-input {
      flex: 1;
      text-align: left;
      &.right {
        text-align: right;
      }
    }
    .xuanzerenlian {
      width: 100%;
      text-align: center;
      margin-top: 10px;
    }
    .block-input-tip {
      font-size: 12px;
      color: #666;
      display: flex;
      flex-direction: row;
      align-items: center;
    }
  }
}
</style>
